<?php

/**
 *    资金管理控制器
 *
 */

class Account_logApp extends BackendApp {

    var $_member_mod;
    var $_account_log_mod;

    function __construct() {
        $this->Account_logApp();
    }

    function Account_logApp() {
        parent::BackendApp();
        $this->_member_mod = & m('member');
        $this->_account_log_mod = & m('account_log');
    }
    
    //查看资金流水
    function index() {
        $search_options = array(
            'user_name' => Lang::get('user_name'),
            'log_text' => Lang::get('log_text'),
            'order_sn' => Lang::get('order_sn'),
        );
        /* 默认搜索的字段是操作名 */
        $field = 'user_name';
        array_key_exists($_GET['field'], $search_options) && $field = $_GET['field'];
        $conditions = $this->_get_query_conditions(array(array(
                'field' => $field, //按用户名,店铺名,支付方式名称进行搜索
                'equal' => 'LIKE',
                'name' => 'search_name',
            ), array(
                'field' => 'type',
                'equal' => '=',
                'name' => 'type',
                'type' => 'numeric',
            ), array(
                'field' => 'add_time',
                'name' => 'add_time_from',
                'equal' => '>=',
                'handler' => 'gmstr2time',
            ), array(
                'field' => 'add_time',
                'name' => 'add_time_to',
                'equal' => '<=',
                'handler' => 'gmstr2time_end',
            ), array(
                'field' => 'money',
                'name' => 'order_amount_from',
                'equal' => '>=',
                'type' => 'numeric',
            ), array(
                'field' => 'money',
                'name' => 'order_amount_to',
                'equal' => '<=',
                'type' => 'numeric',
            ),
        ));
        if($_GET['user_id']){
        	$conditions.=' AND user_id='.intval($_GET['user_id']);
        }
		if($_GET['check_id']){
            $conditions.=' AND if_calcu='.intval($_GET['check_id']);
        }

        $page = $this->_get_page(10);
        $account_log_list = $this->_account_log_mod->find(array(
            'conditions' => 'complete=1' . $conditions,
            'limit' => $page['limit'],
            'order' => "id desc",
            'count' => true));
        $page['item_count'] = $this->_account_log_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);
        
        $this->assign('filtered', $conditions ? 1 : 0); //是否有查询条件
        
        $account_type_list = array(
            ACCOUNT_TYPE_ADMIN => Lang::get('account_type_admin'), //手工操作
            ACCOUNT_TYPE_BUY => Lang::get('account_type_buy'), //购买商品
            ACCOUNT_TYPE_SELLER => Lang::get('account_type_seller'), //出售商品
            ACCOUNT_TYPE_IN => Lang::get('account_type_in'), //账户转入
            ACCOUNT_TYPE_OUT => Lang::get('account_type_out'), //账户转出
            ACCOUNT_TYPE_CZ => Lang::get('account_type_cz'), //账户充值
            ACCOUNT_TYPE_TX => Lang::get('account_type_tx'), //账户提现
            ACCOUNT_TYPE_REFUND_IN => Lang::get('account_type_refund_in'), //账户退款收入,通常为买家退款成功 得到退款
            ACCOUNT_TYPE_REFUND_OUT => Lang::get('account_type_refund_out'), //账户退款收入,通常为卖家退款成功 扣除退款
            ACCOUNT_TYPE_TUIJIAN_BUYER => Lang::get('account_type_tuijian_buyer'),  // 用户推荐注册,注册者购买产品，推荐人会获得佣金，店铺会损失佣金。
            ACCOUNT_TYPE_TUIJIAN_SELLER=> Lang::get('account_type_tuijian_seller'), // 用户推荐注册,注册者成为店主，卖出产品推荐人会获得佣金，店主会损失佣金。
            ACCOUNT_TYPE_TRADE_CHARGES=> Lang::get('account_type_trade_charges'), // 扣除卖家交易佣金
        );
        
        foreach ($account_log_list as $key => $account_log) {
            $account_log_list[$key]['type_name'] = $account_type_list[$account_log['type']];
        }
        
        $this->assign('account_type_list', $account_type_list);
        
        $this->assign('search_options', $search_options);
        $this->assign('account_log_list', $account_log_list);
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                                      'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $this->display('account_log.index.html');
    }

    function statistics() {
        $conditions = $this->_get_query_conditions(array(array(
                'field' => 'user_name', //按用户名,店铺名,支付方式名称进行搜索
                'equal' => '=',
                'name' => 'user_name',
            )
        ));
        
        
        //有效的收入
        $income_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE complete = 1 AND money_flow='income'".$conditions;
        $income_money =  $this->_account_log_mod->getOne($income_sql);
        
        //有效的支出
        $outlay_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE complete = 1 AND money_flow='outlay'".$conditions;
        $outlay_money =  $this->_account_log_mod->getOne($outlay_sql);
        
        //当前可用资金
        $money_sql = "SELECT SUM(money) FROM {$this->_member_mod->table} WHERE 1 = 1".$conditions;
        $money = $this->_member_mod->getOne($money_sql);
        
        //用户冻结资金
        $money_dj_sql = "SELECT SUM(money_dj) FROM {$this->_member_mod->table} WHERE 1 = 1".$conditions;
        $money_dj = $this->_member_mod->getOne($money_dj_sql);
        
        
        $check_1 = array(
            'income_money' => empty($income_money) ? '0.00' : $income_money, #收入资金
            'outlay_money' => empty($outlay_money) ? '0.00' : $outlay_money, #支出资金
            'money' => empty($money) ? '0.00' : $money, #可用资金
            'money_dj' => empty($money_dj) ? '0.00' : $money_dj, #冻结资金
        );
        $this->assign('check_1', $check_1);
        
        //计算方式2
        //管理员增加的资金
        $income_admin_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_ADMIN." AND complete = 1 AND money_flow='income'".$conditions;
        $income_admin = $this->_account_log_mod->getOne($income_admin_sql);
        //管理员减少的资金
        $outlay_admin_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_ADMIN." AND complete = 1 AND money_flow='outlay'".$conditions;
        $outlay_admin = $this->_account_log_mod->getOne($outlay_admin_sql);
        //用户购买产品
        $outlay_buy_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_BUY." AND complete = 1 AND money_flow='outlay'".$conditions;
        $outlay_buy = $this->_account_log_mod->getOne($outlay_buy_sql);
        //店铺出售产品
        $income_seller_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_SELLER." AND complete = 1 AND money_flow='income'".$conditions;
        $income_seller = $this->_account_log_mod->getOne($income_seller_sql);
        //账户转入
        $income_in_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_IN." AND complete = 1 AND money_flow='income'".$conditions;
        $income_in = $this->_account_log_mod->getOne($income_in_sql);
        //账户转出
        $outlay_out_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_OUT." AND complete = 1 AND money_flow='outlay'".$conditions;
        $outlay_out = $this->_account_log_mod->getOne($outlay_out_sql);
        //用户充值
        $income_cz_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_CZ." AND complete = 1 AND money_flow='income'".$conditions;
        $income_cz = $this->_account_log_mod->getOne($income_cz_sql);
        //用户提现审核通过
        $outlay_tx_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_TX." AND complete = 1  AND states = 71 AND money_flow='outlay'".$conditions;
        $outlay_tx = $this->_account_log_mod->getOne($outlay_tx_sql);
        //退款收入
        $income_refund_in_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_REFUND_IN." AND complete = 1 AND money_flow='income'".$conditions;
        $income_refund_in = $this->_account_log_mod->getOne($income_refund_in_sql);
        //退款支出
        $outlay_refund_out_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_REFUND_OUT." AND complete = 1 AND money_flow='outlay'".$conditions;
        $outlay_refund_out = $this->_account_log_mod->getOne($outlay_refund_out_sql);
        //推荐买家购买得到佣金
        $income_tuijian_buyer_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_TUIJIAN_BUYER." AND complete = 1 AND money_flow='income'".$conditions;
        $income_tuijian_buyer = $this->_account_log_mod->getOne($income_tuijian_buyer_sql);
        //推荐买家购买扣除佣金
        $outlay_tuijian_buyer_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_TUIJIAN_BUYER." AND complete = 1 AND money_flow='outlay'".$conditions;
        $outlay_tuijian_buyer = $this->_account_log_mod->getOne($outlay_tuijian_buyer_sql);
        //推荐店铺开店得到佣金
        $income_tuijian_seller_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_TUIJIAN_SELLER." AND complete = 1 AND money_flow='income'".$conditions;
        $income_tuijian_seller = $this->_account_log_mod->getOne($income_tuijian_seller_sql);
        //推荐店铺开店扣除佣金
        $outlay_tuijian_seller_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_TUIJIAN_SELLER." AND complete = 1 AND money_flow='outlay'".$conditions;
        $outlay_tuijian_seller = $this->_account_log_mod->getOne($outlay_tuijian_seller_sql);
        //扣除交易佣金
        $outlay_trade_charges_sql = "SELECT SUM(money) FROM {$this->_account_log_mod->table} WHERE type=".ACCOUNT_TYPE_TRADE_CHARGES." AND complete = 1 AND money_flow='outlay'".$conditions;
        $outlay_trade_charges = $this->_account_log_mod->getOne($outlay_trade_charges_sql);
        
        $check_2 = array(
            'income_admin' => empty($income_admin) ? '0.00' : $income_admin, 
            'outlay_admin' => empty($outlay_admin) ? '0.00' : $outlay_admin, 
            'outlay_buy' => empty($outlay_buy) ? '0.00' : $outlay_buy, 
            'income_seller' => empty($income_seller) ? '0.00' : $income_seller, 
            'income_in' => empty($income_in) ? '0.00' : $income_in, 
            'outlay_out' => empty($outlay_out) ? '0.00' : $outlay_out, 
            'income_cz' => empty($income_cz) ? '0.00' : $income_cz, 
            'outlay_tx' => empty($outlay_tx) ? '0.00' : $outlay_tx, 
            'income_refund_in' => empty($income_refund_in) ? '0.00' : $income_refund_in, 
            'outlay_refund_out' => empty($outlay_refund_out) ? '0.00' : $outlay_refund_out, 
            'income_tuijian_buyer' => empty($income_tuijian_buyer) ? '0.00' : $income_tuijian_buyer, 
            'outlay_tuijian_buyer' => empty($outlay_tuijian_buyer) ? '0.00' : $outlay_tuijian_buyer, 
            'income_tuijian_seller' => empty($income_tuijian_seller) ? '0.00' : $income_tuijian_seller, 
            'outlay_tuijian_seller' => empty($outlay_tuijian_seller) ? '0.00' : $outlay_tuijian_seller, 
            'outlay_trade_charges' => empty($outlay_trade_charges) ? '0.00' : $outlay_trade_charges, 
            'money' => empty($money) ? '0.00' : $money, #可用资金
            'money_dj' => empty($money_dj) ? '0.00' : $money_dj, #冻结资金
        );
        $this->assign('check_2', $check_2);
        
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $this->display('account_log.statistics.html');
    }


    //提现记录
    function txlog() {
        $search_options = array(
            'user_name' => Lang::get('user_name'),
            'order_sn' => Lang::get('order_sn'),
        );
        /* 默认搜索的字段是操作名 */
        $field = 'user_name';
        array_key_exists($_GET['field'], $search_options) && $field = $_GET['field'];
        $conditions = $this->_get_query_conditions(array(array(
                'field' => $field, //按用户名,店铺名,支付方式名称进行搜索
                'equal' => 'LIKE',
                'name' => 'search_name',
            ), array(
                'field' => 'states',
                'equal' => '=',
                'name' => 'status',
                'type' => 'numeric',
            ), array(
                'field' => 'add_time',
                'name' => 'add_time_from',
                'equal' => '>=',
                'handler' => 'gmstr2time',
            ), array(
                'field' => 'add_time',
                'name' => 'add_time_to',
                'equal' => '<=',
                'handler' => 'gmstr2time_end',
            ), array(
                'field' => 'money',
                'name' => 'order_amount_from',
                'equal' => '>=',
                'type' => 'numeric',
            ), array(
                'field' => 'money',
                'name' => 'order_amount_to',
                'equal' => '<=',
                'type' => 'numeric',
            ),
        ));
        $page = $this->_get_page(10);
        $account_log_list = $this->_account_log_mod->find(array(
            'conditions' => 'type='.ACCOUNT_TYPE_TX . $conditions,
            'limit' => $page['limit'],
            'order' => "id desc",
            'count' => true));
        $page['item_count'] = $this->_account_log_mod->getCount();
        $this->_format_page($page);
        $this->assign('search_options', $search_options);
        $this->assign('filtered', $conditions ? 1 : 0); //是否有查询条件
        $this->assign('tx_status_list', array(
            70 => Lang::get('tx_weishenhe'), //未审核
            71 => Lang::get('tx_yishenhe'), //已审核
        ));
        $this->assign('page_info', $page);
        $this->assign('account_log_list', $account_log_list);
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                                      'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->display('account_log.txlog.html');
    }

    //审核操作	
    function tx_view() {
        $log_id = $_GET['log_id'];
        $user_id = $_GET['user_id'];
        $tx_money = trim($_POST['money']);
        $add_time = gmtime();
		$account_log = $this->_account_log_mod->get('id=' . $log_id);
        if (!IS_POST) {
            if (empty($log_id) or empty($user_id)) {
                $this->show_warning('feifacanshu');
                return;
            }
            preg_match('/【交易成功订单号：([^】]*)】/', $account_log['log_text'],$matche);
            $account_log['invoice']=$matche[1];
            $this->assign('account_log', $account_log);
            $this->display('account_log.tx_view.html');
            return;
        } else {
			if(!$account_log['complete']){
            $result=intval($_POST["result"]);
            $money_row = $this->_member_mod->get($user_id);
            $row_money_dj = $money_row['money_dj'];

            if ($row_money_dj < $tx_money) {
                $this->show_warning('feifacanshu');
                return;
            }

            $new_money_dj = $row_money_dj - $tx_money;
                $epaylog = $this->_account_log_mod->get('id=' . $log_id);
            if($result){
                $new_money = array(
                    'money_dj' => $new_money_dj,
                );
                $edit_log = array(
                    //'add_time' => $add_time,
                    'states' => 71, //改变状态为已审核	
                    'complete'=>'1',
                    'log_text'=>'管理员同意了提现请求：'.$epaylog['log_text'].($_POST['invoice']?('【交易成功订单号：'.$_POST['invoice'].'】'):''),
                );
            }else{
                $new_money = array(
                    'money_dj' => $new_money_dj,
                    'money' => $money_row['money']+$tx_money,
                );
                $edit_log = array(
                    //'add_time' => $add_time,
                    'states' => 71, //改变状态为已审核	
                    'complete'=>'1',
                    'money'=>0,
                    'log_text'=>'管理员拒绝了提现请求：'.$epaylog['log_text'],
                );
            }
            /*$new_money = array(
                'money_dj' => $new_money_dj,
            );
            

            $edit_log = array(
                'add_time' => $add_time,
                'states' => 71, //改变状态为已审核	
                'complete'=>'1'
            );*/
            $this->_member_mod->edit('user_id=' . $user_id, $new_money); //读取所有数据库
            $this->_account_log_mod->edit('id=' . $log_id, $edit_log);
            $this->admin_log("审核资金提现[".$tx_money."]",1);
        }else{
            $this->_account_log_mod->edit('id=' . $log_id, 'log_text="'. preg_replace('/【交易成功订单号：[^】]*】/', ($_POST['invoice']?('【交易成功订单号：'.$_POST['invoice'].'】'):''), $account_log['log_text']).'"');
            $this->admin_log("编辑资金提现[".$tx_money."]",1);
        }
        }
        $this->show_message('shenhechenggong', 'fanhuiliebiao', 'index.php?app=account_log&act=txlog');
    }

    function setting() {
        $model_setting = &af('settings');
        $setting = $model_setting->getAll(); //载入系统设置数据
        if (!IS_POST) {
            $this->assign('setting', $setting);
            $this->display('account_log.setting.html');
        } else {
            //交易佣金比例
            $data['payment_trade_charges_ratio'] = empty($_POST['payment_trade_charges_ratio']) ? 0 : round($_POST['payment_trade_charges_ratio'], 3); 
            //支付宝配置文件
            $data['payment_alipay_seller_email'] = trim($_POST['payment_alipay_seller_email']);
            $data['payment_alipay_partner'] = trim($_POST['payment_alipay_partner']);
            $data['payment_alipay_key'] = trim($_POST['payment_alipay_key']);



            //财付通配置文件
            $data['payment_tenpay_bargainor_id'] = trim($_POST['payment_tenpay_bargainor_id']);
            $data['payment_tenpay_key'] = trim($_POST['payment_tenpay_key']);

            //微信配置信息
            $data['payment_wx_appid'] = trim($_POST['payment_wx_appid']); 
            $data['payment_wx_key'] = trim($_POST['payment_wx_key']);
            $data['payment_wx_mch_id'] = trim($_POST['payment_wx_mch_id']);
            $data['payment_wx_secret'] = trim($_POST['payment_wx_secret']);
            
            //网银在线支付配置信息
            $data['payment_jdpay_merchantNum'] = trim($_POST['payment_jdpay_merchantNum']);
            $data['payment_jdpay_md5Key'] = trim($_POST['payment_jdpay_md5Key']);
            $data['payment_jdpay_desKey'] = trim($_POST['payment_jdpay_desKey']);
            
            //unionpay在线支付
            $data['payment_unionpay_merId'] = trim($_POST['payment_unionpay_merId']);#商户号
            $data['payment_unionpay_certpwd'] = trim($_POST['payment_unionpay_certpwd']);#证书密码
            $payment_unionpay_cert = $this->_upload_cert();
            if($payment_unionpay_cert){
                $data['payment_unionpay_cert'] = $payment_unionpay_cert;#上传证书
            }
            
            $this->admin_log(Lang::get('Set_payment_info'),1);
			
            $model_setting->setAll($data);
            $this->show_message('setting_successed');
        }
    }
    
    function _upload_cert() {
        $file = $_FILES['payment_unionpay_cert'];
        if ($file['error'] == 0 && $file['type']=='application/x-pkcs12') {
            $cert_urls = ROOT_PATH.'/includes/payments/epayunionpay/certs/acp_sign.pfx';
            move_uploaded_file($file["tmp_name"],$cert_urls);
            return $cert_urls;
        }
        return FALSE;
    }
}
